package in.muton.edushare.academics.panels;

import in.muton.edushare.academics.panels.GradePanelUtil.GradeKeyHelper;
import in.muton.edushare.auth.roles.CourseRoleCheck;
import in.muton.edushare.auth.roles.DeptRoleCheck;
import in.muton.edushare.pages.EduShareBasePage;
import in.muton.edushare.pages.common.EdusharePanel;
import in.muton.edushare.wicket.models.CayenneModel;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.apache.wicket.markup.html.WebMarkupContainer;

import com.edushare.common.vo.CourseInstances;
import com.edushare.common.vo.Departments;

public class EntityGradePanel extends EdusharePanel {

	private CayenneModel<CourseInstances> courseInst;
	private CayenneModel<Departments> dept;
	private List<GradeKeyHelper> tupleList = new ArrayList<GradeKeyHelper>();
	private boolean initialized = false;
	private boolean visibility = false;
	private int activeMode = VIEW_MODE;
	public static final int EDIT_MODE 	=	10;
	public static final int VIEW_MODE 	=	20;
	
	public EntityGradePanel(String id, EduShareBasePage page, Departments dept) {
		super(id, page);
		this.dept = new CayenneModel<Departments>(dept);
		DeptRoleCheck drc = new DeptRoleCheck(dept, getLoggedInUser());
		visibility = drc.isAdmin();
		init(page);
	}

	public EntityGradePanel(String id, EduShareBasePage page, CourseInstances course) {
		super(id, page);
		this.courseInst = new CayenneModel<CourseInstances>(course);
		CourseRoleCheck crc = new CourseRoleCheck(course, getLoggedInUser());
		visibility = crc.isAdmin()||crc.isTeacher();
		init(page);
	}

	private void init(EduShareBasePage page){
		getTupleList();
		add(new WebMarkupContainer("noGradePanel").setVisible(tupleList.size()==0));
		WebMarkupContainer wmc = new WebMarkupContainer("gradePanel");
		add(wmc.setVisible(tupleList.size()>0));
		wmc.add(new EntityGradeEdit("panel1", this, page));
		wmc.add(new EntityGradeView("panel2", this, page, visibility));
	}
	
	public void setActiveMode(int activeMode) {
		this.activeMode = activeMode;
	}

	public int getActiveMode() {
		return activeMode;
	}
	
	public boolean isInitialized() {
		return initialized;
	}

	public void setInitialized(boolean initialized) {
		this.initialized = initialized;
	}

	public List<GradeKeyHelper> getTupleList() {
		if(!initialized){
			if(courseInst != null){
				tupleList = GradePanelUtil.getTuples(courseInst.getObject());
			}else if(dept != null){
				tupleList = GradePanelUtil.getTuples(dept.getObject());
			}else{
				tupleList = new ArrayList<GradeKeyHelper>();
			}
			Collections.sort(tupleList);
			Collections.reverse(tupleList);
			setInitialized(true);
		}
		return tupleList;
	}

	private static final long serialVersionUID = -3033831478187953296L;
}
